package com.openharmony.filepicker.slice;

import com.openharmony.filepicker.ResourceTable;
import com.openharmony.filepicker.adapter.SampleProvider;
import com.openharmony.filepicker.bean.FileItemBeanImpl;
import com.openharmony.filepicker.config.AbstractFileFilter;
import com.openharmony.filepicker.config.FilePickerConfig;
import com.openharmony.filepicker.config.FilePickerManager;
import com.openharmony.filepicker.engine.ImageEngine;
import com.openharmony.filepicker.filetype.AudioFileType;
import com.openharmony.filepicker.filetype.RasterImageFileType;
import com.openharmony.filepicker.utils.ImageUtil;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.ListContainer;
import ohos.app.Context;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.utils.net.Uri;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

public class HomeAbilitySlice extends AbilitySlice {

    static final HiLogLabel LABEL = new HiLogLabel(HiLog.LOG_APP, 0x00201, "MY_TAG");

    /**
     * 自定义文件过滤器
     */
    private AbstractFileFilter fileFilter;

    private SampleProvider sampleProvider;
    private ListContainer sampleResultLC;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_home);

        initInfo();
        initListener();

        HiLog.error(LABEL, "--- my load path test");
    }

    private void initListener() {

        // 单选
        findComponentById(ResourceTable.Id_btn_single)
                .setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {

                FilePickerManager
                        .INSTANCE()
                        .from(HomeAbilitySlice.this)
                        .imageEngine(new ImageEngine() {
                            @Override
                            public void loadImage(Context context,
                                                  Image image,
                                                  String url,
                                                  int placeholder) {
                                // 应该使用 loadImage 传递过来的 context，而不是您自己的 context
                                // You should use the context passed by loadImage(),
                                // not your own context
                                ImageUtil
                                        .loadImage(image,
                                                Uri.parse(url),
                                                ResourceTable.Media_ic_image_file);
                            }
                        })
                        .enableSingleChoice()
                        .forResult(FilePickerManager.REQUEST_CODE);
            }
        });

        //只展示文件夹
        findComponentById(ResourceTable.Id_btn_only_dir)
                .setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                FilePickerManager
                        .INSTANCE()
                        .from(HomeAbilitySlice.this)
                        .setTheme(0)
                        .filter(new AbstractFileFilter() {
                            @Override
                            public ArrayList<FileItemBeanImpl> doFilter(
                                    ArrayList<FileItemBeanImpl> listData
                            ) {

                                ArrayList<FileItemBeanImpl> result = new ArrayList<>();
                                for (FileItemBeanImpl item : listData) {
                                    if (item.isDir()) {
                                        result.add(item);
                                    }
                                }
                                return result;
                            }
                        })
                        .forResult(FilePickerManager.REQUEST_CODE);
            }
        });

        //只展示图片
        findComponentById(ResourceTable.Id_btn_only_image)
                .setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                FilePickerManager
                        .INSTANCE()
                        .from(HomeAbilitySlice.this)
                        .setTheme(0)
                        .filter(new AbstractFileFilter() {
                            @Override
                            public ArrayList<FileItemBeanImpl> doFilter(
                                    ArrayList<FileItemBeanImpl> listData
                            ) {

                                ArrayList<FileItemBeanImpl> result = new ArrayList<>();
                                for (FileItemBeanImpl itemBean : listData) {
                                    if (itemBean.isDir() || itemBean
                                            .getFileType() instanceof RasterImageFileType) {
                                        result.add(itemBean);
                                    }
                                }
                                return result;
                            }
                        })
                        .forResult(FilePickerManager.REQUEST_CODE);
            }
        });

        // 显示隐藏文件，. 符号开头的
        findComponentById(ResourceTable.Id_btn_display_hidden)
                .setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                FilePickerManager
                        .INSTANCE()
                        .from(HomeAbilitySlice.this)
                        .setTheme(0)
                        .showHiddenFiles(true)
                        .forResult(FilePickerManager.REQUEST_CODE);
            }
        });

        // 单选文件夹
        findComponentById(ResourceTable.Id_btn_single_dir)
                .setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                FilePickerManager
                        .INSTANCE()
                        .from(HomeAbilitySlice.this)
                        .enableSingleChoice()
                        .setTheme(0)
                        .filter(new AbstractFileFilter() {
                            @Override
                            public ArrayList<FileItemBeanImpl> doFilter(
                                    ArrayList<FileItemBeanImpl> listData
                            ) {
                                ArrayList<FileItemBeanImpl> result = new ArrayList<>();
                                for (FileItemBeanImpl item : listData) {
                                    if (item.isDir()) {
                                        result.add(item);
                                    }
                                }
                                return result;
                            }
                        })
                        .skipDirWhenSelect(false)
                        .forResult(FilePickerManager.REQUEST_CODE);
            }
        });

        // 多选文件
        findComponentById(ResourceTable.Id_btn_multi_file)
                .setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                FilePickerManager
                        .INSTANCE()
                        .from(HomeAbilitySlice.this)
                        .setTheme(0)
                        .maxSelectable(2)
                        .forResult(FilePickerManager.REQUEST_CODE);
            }
        });

        // 多选文件夹
        findComponentById(ResourceTable.Id_btn_multi_dir)
                .setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                FilePickerManager
                        .INSTANCE()
                        .from(HomeAbilitySlice.this)
                        .setTheme(0)
                        .maxSelectable(2)
                        .filter(new AbstractFileFilter() {
                            @Override
                            public ArrayList<FileItemBeanImpl> doFilter(
                                    ArrayList<FileItemBeanImpl> listData
                            ) {
                                ArrayList<FileItemBeanImpl> result = new ArrayList<>();
                                for (FileItemBeanImpl item : listData) {
                                    if (item.isDir()) {
                                        result.add(item);
                                    }
                                }
                                return result;
                            }
                        })
                        .skipDirWhenSelect(false)
                        .forResult(FilePickerManager.REQUEST_CODE);
            }
        });

        // 自定义文件类型
        findComponentById(ResourceTable.Id_btn_custom_file_type)
                .setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                FilePickerManager.INSTANCE()
                        .from(HomeAbilitySlice.this)
                        .setTheme(0)
                        .registerFileType(Arrays.asList(new AudioFileType()))
                        .forResult(FilePickerManager.REQUEST_CODE);
            }
        });

        // 自定义根目录
        findComponentById(ResourceTable.Id_btn_custom_root_path)
                .setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                FilePickerManager
                        .INSTANCE()
                        .from(HomeAbilitySlice.this)
                        .storageType("下载", FilePickerConfig.STORAGE_CUSTOM_ROOT_PATH)
                        .setTheme(0)
                        .setCustomRootPath("/storage/emulated/0/Download")
                        .forResult(FilePickerManager.REQUEST_CODE);
            }
        });
    }

    private void initInfo() {
        fileFilter = new AbstractFileFilter() {
            @Override
            public ArrayList<FileItemBeanImpl> doFilter(ArrayList<FileItemBeanImpl> listData) {
                Iterator<FileItemBeanImpl> iterator = listData.iterator();
                while (iterator.hasNext()) {
                    FileItemBeanImpl item = iterator.next();
                    // 如果是文件夹则略过
                    if (item.isDir()) {
                        continue;
                    }
                    // 判断文件类型是否是图片
                    if (item.getFileType() instanceof RasterImageFileType) {
                        iterator.remove();
                    }
                }
                return listData;
            }
        };


        sampleResultLC = (ListContainer) findComponentById(ResourceTable.Id_list_home);
        sampleProvider = new SampleProvider(getContext());
        sampleResultLC.setItemProvider(sampleProvider);
    }

    @Override
    protected void onAbilityResult(int requestCode, int resultCode, Intent resultData) {
        super.onAbilityResult(requestCode, resultCode, resultData);
        switch (requestCode) {
            case FilePickerManager.REQUEST_CODE:
                if (resultCode == FilePickerManager.RESULT_OK) {
                    List<String> strings = FilePickerManager.INSTANCE().obtainData(true);
                    System.out.println("=== get result list : " + strings.size());
                    if (strings.size() > 0) {
                        System.out.println("=== get first : " + strings.get(0));
                    }
                    sampleProvider.setInfo(strings);
                }
                break;
            default:
                break;
        }
    }
}
